package br.com.tiespec.ejb.Dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.tiespec.model.Enum.TipoSortOrder;
import br.com.tiespec.model.Modelo.Documento;
import br.com.tiespec.model.Util.DAOException;

@Stateless(mappedName = "DocumentoDAO")
public class DocumentoDAO extends DAO {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public List<Documento> listarDocumento(int first, int pageSize, String sortField,
			TipoSortOrder sortOrder, Long idArtefato, String nome) {
		List<Documento> aList = new ArrayList<Documento>();
		try {
			begin();
			Criteria criteria = this.session.createCriteria(Documento.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.add(Restrictions.eq("artefato.id", idArtefato));
			
			if (isNullOrBlank(nome))
				criteria.add(Restrictions.eq("nome", "%" + nome + "%"));
			
			criteria = montaPaginacaoSimples(criteria, first, pageSize, sortField, sortOrder);
			
			aList = criteria.list();
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return aList;
	}

	public Integer countDocumento(Long idArtefato, String nome) {
		Integer count = 0;
		try {
			begin();
			Criteria criteria = this.session.createCriteria(Documento.class)
					.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
					.add(Restrictions.eq("artefato.id", idArtefato))
					.setProjection(Projections.rowCount());
			
			if (isNullOrBlank(nome))
				criteria.add(Restrictions.eq("nome", "%" + nome + "%"));
			
			count = Integer.parseInt(criteria.uniqueResult().toString());
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return count;
	}

	public Documento selecionar(Long id) {
		Documento aInstance = new Documento();
		try {
			begin();
			aInstance = (Documento) this.session.createCriteria(Documento.class)
					.add(Restrictions.eq("id", id)).uniqueResult();
			commit();
			fecharConexao();
		} catch (Exception e){
			e.printStackTrace();
			fecharConexao();
		}
		return aInstance;
	}

	public void remover(Long id) throws DAOException {
		delete(Documento.class, id);
	}
}